package com.platform.modules.cpt.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DownloadUtils;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.UUID;
import com.platform.dao.AttachmentDao;
import com.platform.entity.Attachment;
import com.platform.modules.cpt.dao.CptAcceptanceConditionDao;
import com.platform.modules.cpt.entity.CptAcceptanceConditionEntity;
import com.platform.modules.cpt.entity.CptAcceptanceEntity;
import com.platform.modules.cpt.service.CptAcceptanceConditionService;
import com.platform.modules.cpt.service.CptAcceptanceService;
import com.platform.util.DocUtil;

@Service
public class CptAcceptanceConditionServiceImpl extends ServiceImpl<CptAcceptanceConditionDao, CptAcceptanceConditionEntity> implements CptAcceptanceConditionService {

    private static final Logger logger = LoggerFactory.getLogger(CptAcceptanceConditionServiceImpl.class);
    
    @Autowired
    private CptAcceptanceService cptAcceptanceService;
    @Autowired
    private DocUtil docUtil;
    @Autowired
    private AttachmentDao attachmentDao;

    @Override
    public boolean save(CptAcceptanceConditionEntity entity) {
        if(StringUtils.isBlank(entity.getId())) {
        	entity.setCreateTime(new Date());
            this.baseMapper.insert(entity);
        }else {
        	entity.setUpdateTime(new Date());
            this.baseMapper.updateById(entity);
        }
        return true;
    }

    @Override
    public CptAcceptanceConditionEntity queryOne(Map<String, Object> params) {
        params.put("sidx", "CREATE_TIME");
        params.put("asc", false);
        List<CptAcceptanceConditionEntity> list = baseMapper.selectList(params);
        if(list==null || list.isEmpty()){
            return null;
        }else {
            return list.get(0);
        }
    }

	@Override
	public Map<String, Object> createGcjgysjdtjhcjl1File(CptAcceptanceEntity cptAcceptanceEntity) {
		Map<String, Object> result = new HashMap<>();
		
		CptAcceptanceEntity cptAcceptance = cptAcceptanceService.getById(cptAcceptanceEntity.getId());
		if(null==cptAcceptance) {
			throw new BusinessException("未找到工程竣工验收监督申请记录");
		}
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("cptId", cptAcceptanceEntity.getId());
		
		CptAcceptanceConditionEntity cptAcceptanceCondition = queryOne(m);
		if(null==cptAcceptanceCondition) {
			throw new BusinessException("未找到工程竣工验收监督条件核查记录");
		}
		
		//生成文件前, 删除带签名文件
		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptAcceptanceEntity.getId(),"CPT_ACCPTANCE_FILES_GCJGYSJDTJHCJL1");
		if(null!=list && list.size()>0) {
			for(int i=0; i<list.size(); i++) {
				Attachment attachment = list.get(i);
				docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
			}
		}

        
        Calendar cal=Calendar.getInstance();
        cal.setTime(cptAcceptanceCondition.getCreateTime());
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH);//获取月份
        int day=cal.get(Calendar.DATE);//获取日
        int hour=cal.get(Calendar.HOUR);//小时
        int minute=cal.get(Calendar.MINUTE);//分           
        int second=cal.get(Calendar.SECOND);//秒 
        
		
        //组装参数
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("ag1", cptAcceptance.getPrjName());
		data.put("ag2", cptAcceptance.getUnitPrjName());
		data.put("ag3", cptAcceptanceCondition.getVouchFile());
		data.put("ag4", cptAcceptanceCondition.getQuestions());
		data.put("ag5", cptAcceptanceCondition.getSuggest());
		data.put("ag6", ""+year);
		data.put("ag7", ""+(month+1));
		data.put("ag8", ""+day);
		//替换null值
		processMap(data);
		
		//导出PDF
		String ftlFile = "jgys/gcjgysjdtjhcjl1.xml";
		String fileName = DownloadUtils.exportPDF(data, ftlFile);
		
		//转换文件对象类型
        FileItem fileItem = createFileItem(fileName + ".pdf");
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        
        //上传文件
        String attId = docUtil.createAtt(mfile, "CPT_ACCPTANCE_FILES_GCJGYSJDTJHCJL1", cptAcceptanceEntity.getId());
        
        result.put("fileName",fileName);
        result.put("attId",attId);
		return result;
	}
	

	@Override
	public Map<String, Object> createGcjgysjdtjhcjl2File(CptAcceptanceEntity cptAcceptanceEntity) {
		Map<String, Object> result = new HashMap<>();
		
		CptAcceptanceEntity cptAcceptance = cptAcceptanceService.getById(cptAcceptanceEntity.getId());
		if(null==cptAcceptance) {
			throw new BusinessException("未找到工程竣工验收监督申请记录");
		}
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("cptId", cptAcceptanceEntity.getId());
		
		CptAcceptanceConditionEntity cptAcceptanceCondition = queryOne(m);
		if(null==cptAcceptanceCondition) {
			throw new BusinessException("未找到工程竣工验收监督条件核查记录");
		}
		
		//生成文件前, 删除带签名文件
		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptAcceptanceEntity.getId(),"CPT_ACCPTANCE_FILES_GCJGYSJDTJHCJL2");
		if(null!=list && list.size()>0) {
			for(int i=0; i<list.size(); i++) {
				Attachment attachment = list.get(i);
				docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
			}
		}
        
        Calendar cal=Calendar.getInstance();
        cal.setTime(cptAcceptanceCondition.getCreateTime());
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH);//获取月份
        int day=cal.get(Calendar.DATE);//获取日
        int hour=cal.get(Calendar.HOUR);//小时
        int minute=cal.get(Calendar.MINUTE);//分           
        int second=cal.get(Calendar.SECOND);//秒 
        
		
        //组装参数
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("ag1", cptAcceptanceCondition.getC1());
		data.put("ag2", cptAcceptanceCondition.getC2());
		data.put("ag3", cptAcceptanceCondition.getC3());
		data.put("ag4", cptAcceptanceCondition.getC4());
		data.put("ag5", cptAcceptanceCondition.getC5());
		data.put("ag6", cptAcceptanceCondition.getC6());
		data.put("ag7", cptAcceptanceCondition.getC7());
		data.put("ag8", cptAcceptanceCondition.getC8());
		data.put("ag9", cptAcceptanceCondition.getC9());
		data.put("ag10", cptAcceptanceCondition.getC10());
		data.put("ag11", cptAcceptanceCondition.getC11());
		data.put("ag12", cptAcceptanceCondition.getConclusion());
		data.put("ag13", ""+year);
		data.put("ag14", ""+(month+1));
		data.put("ag15", ""+day);
		//替换null值
		processMap(data);
		
		//导出PDF
		String ftlFile = "jgys/gcjgysjdtjhcjl2.xml";
		String fileName = DownloadUtils.exportPDF(data, ftlFile);
		
		//转换文件对象类型
        FileItem fileItem = createFileItem(fileName + ".pdf");
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        
        //上传文件
        String attId = docUtil.createAtt(mfile, "CPT_ACCPTANCE_FILES_GCJGYSJDTJHCJL2", cptAcceptanceEntity.getId());
        
        result.put("fileName",fileName);
        result.put("attId",attId);
		return result;
	}

	@Override
	public void downloadGcjgysjdtjhcjlFile(String cptId, HttpServletRequest request, HttpServletResponse response, String attCode) {
		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到工程竣工验收监督通知书");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		
		
		InputStream is = docUtil.getFile(attId);
    	
		// 实现文件下载
       byte[] buffer = new byte[1024];
       BufferedInputStream bis = null;
       try {
           bis = new BufferedInputStream(is);
           OutputStream os = response.getOutputStream();
           int i = bis.read(buffer);
           while (i != -1) {
               os.write(buffer, 0, i);
               i = bis.read(buffer);
           }
       }
       catch (Exception e) {
           
       }
       finally {
           if (bis != null) {
               try {
                   bis.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if (is != null) {
               try {
               	is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
		
	}

	@Override
	public void signGcjgysjdtjhcjlFile(HttpServletRequest request, String cptId, String attCode, String FileName) {
		
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("cptId", cptId);		
		CptAcceptanceConditionEntity cptAcceptanceCondition = queryOne(m);
		if(null==cptAcceptanceCondition) {
			throw new BusinessException("未找到工程竣工验收监督条件核查记录");
		}
		
		//查询并删除所有 工程竣工验收监督条件核查记录一
		List<Attachment> list = docUtil.getAttListByAttBusinessIdAndAttCode(cptId,attCode);
		if(null!=list && list.size()>0) {
			for(int i=0; i<list.size(); i++) {
				Attachment attachment = list.get(i);
				docUtil.deleteAtts(Arrays.asList(attachment.getId().split(",")));
			}
		}
		
    	
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        Map<String, MultipartFile> map = multipartRequest.getFileMap();
        MultipartFile attach = (MultipartFile) map.values().toArray()[0];
        InputStream inputStream = null;
        try {
            inputStream = attach.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String attId2 = UUID.getId();
        docUtil.createAtt(attId2, null, null, attCode, cptId, FileName, inputStream);
        
        //更新监督条件 签名状态为 2-已签名
        cptAcceptanceCondition.setIsSign("2");
        baseMapper.updateById(cptAcceptanceCondition);
	}
    


	//获取FileItem对象：
	private FileItem createFileItem(String filePath) {
	    FileItemFactory factory = new DiskFileItemFactory(16, null);
	    String textFieldName = "textField";
	    int num = filePath.lastIndexOf(".");
	    String extFile = filePath.substring(num);
	    FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName");
	    File newfile = new File(filePath);
	    int bytesRead = 0;
	    byte[] buffer = new byte[8192];
	    try {
	        FileInputStream fis = new FileInputStream(newfile);
	        OutputStream os = item.getOutputStream();
	        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
	            os.write(buffer, 0, bytesRead);
	        }
	        os.close();
	        fis.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return item;
	}

	@Override
	public void downloadSignGcjgysjdtjhcjlFile(String cptId, HttpServletRequest request, HttpServletResponse response,
			String attCode) {

		List<Attachment> attList = docUtil.getAttListByAttBusinessIdAndAttCode(cptId, attCode);
		if(null==attList || attList.size()<1) {
			throw new BusinessException("未找到工程竣工验收监督核查文件");
		}
		String attId = null;
		for(int i=0; i<attList.size(); i++) {
			Attachment attachment = attList.get(i);
			attachment.getName();
			attId = attachment.getId();
		}
		InputStream is = docUtil.getFile(attId);
    	Attachment attachment = attachmentDao.selectById(attId);
    	
    	//实现文件下载
		byte[] buffer = new byte[1024];
		BufferedInputStream bis = null;
		try {
			response.setHeader("content-type", "application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(attachment.getName(), "UTF-8"));
			response.setContentType("application/octet-stream");

			bis = new BufferedInputStream(is);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private void processMap(Map<String,Object> map) {
		//遍历map 
		for(Map.Entry<String, Object> entry : map.entrySet()) {
			//替换Null值, 防止生成doc文件时报错
            if(map.get(entry.getKey())==null) {
            	map.put(entry.getKey(), "");
            }
		}
	}
}
